package cn.chaos.nio02;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;

public class ByteBuffExample01 {
    
    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(8);

        System.out.println(buffer.position());
        buffer.put((byte)'H');
        System.out.println(buffer.position());
        buffer.put((byte)'e');
        System.out.println(buffer.position());
        buffer.put(0, (byte)'M');
        System.out.println(buffer.position());
        
        // 等同于 buffer.flip()
        buffer.limit(buffer.position()).position(0);
        
        // rewind() 函数与 flip() 类似。
        // 但不影响上界属性，只是将位置设为 0 
        // 可以用 rewind() 后退，重读数据。
        
        // hasRemaining() 会搞死你是否达到缓冲区上界
        
        for (int i = 0; buffer.hasRemaining(); i++) {
            byte b = buffer.get();
            System.out.println("b = "+ b +" = "+ (char)b + "; remaining = "+ buffer.remaining());
            byte b2 = buffer.get(0);
            System.out.println("b2 = "+ b2 +" = "+ (char)b2 + "; remaining = "+ buffer.remaining());
            
            byte b3 = buffer.get(i);
            System.out.println("b3 = "+ b3 +" = "+ (char)b3 + "; remaining = "+ buffer.remaining());
        }
        
        // clear 函数将缓冲区重置为空状态。
        // 不清空数据，仅仅将上界设为容量值，将位置设为 0 。
        buffer.clear();

        System.out.println(buffer.hasArray());
        
        StringBuilder hellowrold = new StringBuilder("Hello World");
        CharBuffer charBuffer = CharBuffer.wrap(hellowrold);
       
        System.out.println(charBuffer.isReadOnly());
        // charBuffer.put(0, (char)'W');
        System.out.println(charBuffer.isDirect());
        
        ByteBuffer direct = ByteBuffer.allocateDirect(8192);
        System.out.println(direct.isDirect());
        
    }

}
